package com.cloudbroker.bcs.platform.dav.middle.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.util.DateTimeUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.history.result.HistoryListDataForSearch;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.question.vo.QuesAnswerUpdateForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.chat.vo.RollingMsgUpdateForm;
import com.cloudbroker.bcs.platform.dav.middle.entity.Answer;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.Question;
import com.cloudbroker.bcs.platform.dav.middle.entity.RollingMsg;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointMsg;
import com.cloudbroker.bsc.common.search.common.SearchEngineAdapterClient;

public class SearchUtil {
    
    private static volatile SearchUtil instance;
    
    public static ExecutorService pool;
    
    private static final String TABLE_NAME = "history";
    private static final String QUESTION_TABLE_PREFIX = "question_";
    private static final String VIEWPOINT_TABLE_PREFIX = "viewpoint_";
    private static final String ROLLINGMSG_TABLE_PREFIX = "rollingmsg_";
    public static final Integer QUESTION_TYPE = 0;
    public static final Integer ROLLINGMSG_TYPE = 1;
    public static final Integer VIEWPOINT_TYPE = 2;
    private static final Logger logger = LoggerFactory.getLogger(SearchUtil.class);
    static {
        pool = Executors.newFixedThreadPool(10);
    }
    
    public static SearchUtil getInstance() {
        if (instance == null) {
            instance = new SearchUtil();
        }
        return instance;
    }
    
    private SearchUtil() {
        
    }
    
    /**
     * 获取单个自媒体观点的详情
     * @param selfViewpoinId
     * @return
     */
    public Map<String, Object> getSelfViewpointById(String selfViewpoinId) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("id", "es equals " + selfViewpoinId);
        List<Map> listSearch = SearchEngineAdapterClient.getSearchEngineAdapter()
                .query("history", params, 0, 10, "2", "desc");
        if (listSearch == null || listSearch.size() == 0) {
            return null;
        }
        return listSearch.get(0);
    }
    
    /**
     * 查询自媒体列表
     * @param key_word
     * @param page_no
     * @param page_size
     * @param field_sort
     * @param sort_order
     * @return
     */
    public List<Map<String, Object>> getSelfMediaList(String key_word, Integer page_no, Integer page_size,
            String field_sort, String sort_order, String viewpoint_review_type) {
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, String> params = new HashMap<String, String>();
        if (!StringUtil.isEmpty(key_word)) {
            params.put("orCondition", "es should viewpoint_title == " + key_word + " or broker_name == " + key_word);
        }
        params.put("info_type", "es equals " + 2);
        params.put("public_flag", "es equals " + 1);
        if ("1".equals(viewpoint_review_type)) {
            params.put("public_review_status", "es equals " + viewpoint_review_type);
        }
        List<Map> listSearch = SearchEngineAdapterClient.getSearchEngineAdapter().query("history", params,
                (page_no - 1) * page_size, page_size, field_sort, sort_order);
        if (listSearch != null && listSearch.size() > 0) {
            for (Map map : listSearch) {
                list.add(map);
            }
        }
        return list;
    }
    
    /*
     * 更新自媒体观点审核状态到引擎
     * @param viewpointId
     * @param public_review_status
     */
    public void updateSearchById(final String viewpointId, final String public_review_status) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                HistoryListDataForSearch data = new HistoryListDataForSearch();
                data.setPublic_review_status(public_review_status);
                boolean b = SearchEngineAdapterClient.getSearchEngineAdapter().update(TABLE_NAME,
                        VIEWPOINT_TABLE_PREFIX + viewpointId, data);
                try {
                    if (b) {
                        logger.info("更新观点说" + TABLE_NAME + "，row_id：" + viewpointId.toString() + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("更新观点说" + TABLE_NAME + "，row_id：" + viewpointId.toString() + "到搜索引擎失败",
                            e.getMessage());
                }
                
            }
        });
    }
    
    /*
     * 问与答添加到搜索引擎
     */
    public void addToSearch(final Question q, final Answer answer, final String customer_name,
            final String broker_name, final String broker_avatar) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                HistoryListDataForSearch data = new HistoryListDataForSearch();
                data.setId(q.getQuestion_id());
                data.setTag_id(q.getQuestion_tag());
                data.setContent(q.getQuestion_content());
                data.setSend_time(DateTimeUtil.toString(q.getCreate_time(),
                        DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
                data.setPositionStrByTime(q.getPosition_str());
                data.setCustomer_name(customer_name);
                data.setAnswer_tag(answer.getAnswer_tag());
                data.setAnswer_content(answer.getAnswer_content());
                data.setAnswer_time(DateTimeUtil.toString(answer.getCreate_time(),
                        DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
                data.setBroker_id(q.getBroker_id());
                data.setBroker_name(broker_name);
                data.setBroker_avatar(broker_avatar);
                data.setInfo_type(QUESTION_TYPE);
                boolean b = SearchEngineAdapterClient.getSearchEngineAdapter().save(TABLE_NAME,
                        QUESTION_TABLE_PREFIX + q.getQuestion_id(), data);
                try {
                    if (b) {
                        logger.info("新增问与答" + TABLE_NAME + "，row_id：" + q.getQuestion_id() + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("新增问与答" + TABLE_NAME + "，row_id：" + q.getQuestion_id() + "到搜索引擎失败", e.getMessage());
                }
            }
        });
    }
    
    /*
     * 
     * 直播添加到搜索引擎
     */
    public void addToSearch(final RollingMsg rollingMsg, final String broker_name, final String broker_avatar) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                String position_str = PositionStrUtil.getPositionStr();
                Date now = new Date();
                HistoryListDataForSearch data = new HistoryListDataForSearch();
                data.setBroker_id(rollingMsg.getBroker_id());
                data.setSend_time(DateTimeUtil.toString(now, DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
                data.setPositionStrByTime(position_str);
                data.setContent(rollingMsg.getMsg_content());
                data.setId(rollingMsg.getRollingmsg_id());
                data.setBroker_name(broker_name);
                data.setBroker_avatar(broker_avatar);
                data.setInfo_type(ROLLINGMSG_TYPE);
                boolean b = SearchEngineAdapterClient.getSearchEngineAdapter().save(TABLE_NAME,
                        ROLLINGMSG_TABLE_PREFIX + rollingMsg.getRollingmsg_id(), data);
                try {
                    if (b) {
                        logger.info("新增直播" + TABLE_NAME + "，row_id：" + rollingMsg.getRollingmsg_id() + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("新增直播" + TABLE_NAME + "，row_id：" + rollingMsg.getRollingmsg_id() + "到搜索引擎失败",
                            e.getMessage());
                }
            }
        });
    }
    
    /*
     * 观点添加到搜索引擎
     */
    public void addToSearch(final ViewpointMsg msg, final Broker broker, final Integer publicFlag,
            final String checkFlag) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                System.out.println(msg);
                HistoryListDataForSearch data = new HistoryListDataForSearch();
                Long viewpointId = msg.getViewpoint_id();
                String position_str = PositionStrUtil.getPositionStr();
                data.setId(viewpointId);
                data.setBroker_id(broker.getBroker_id());
                //存储到搜索引擎时将内容解析出来
                msg.setViewpoint_content(ViewpointMsgFormatUtil.parseContext(msg.getViewpoint_content()));
                data.setContent(msg.getViewpoint_content());
                data.setLabel(msg.getViewpoint_abstract());
                data.setTag_id(String.valueOf(msg.getViewpoint_tag()));
                data.setTag_name(msg.getViewpoint_tag_name());
                data.setSend_time(DateTimeUtil.toString(msg.getSend_time(),
                        DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
                data.setPositionStrByTime(position_str);
                data.setImg_audio(ValueUtil.getString(msg.getViewpoint_img_audio()));
                data.setBroker_name(broker.getBroker_name());
                data.setBroker_avatar(broker.getBroker_avatar());
                data.setInfo_type(VIEWPOINT_TYPE);
                data.setPublic_flag(ValueUtil.getString(publicFlag));
                JSONObject contentJson = JSON.parseObject(msg.getViewpoint_content());
                String viewpoint_title = contentJson.getString("title");
                data.setViewpoint_title(viewpoint_title);
                data.setPublic_review_status(checkFlag);
                boolean b = SearchEngineAdapterClient.getSearchEngineAdapter().save(TABLE_NAME,
                        VIEWPOINT_TABLE_PREFIX + msg.getViewpoint_id(), data);
                try {
                    if (b) {
                        logger.info("新增观点" + TABLE_NAME + "，row_id：" + msg.getViewpoint_id() + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("新增观点" + TABLE_NAME + "，row_id：" + msg.getViewpoint_id() + "到搜索引擎失败",
                            e.getMessage());
                }
                
            }
        });
    }
    
    /*
     * 问与答更新到引擎
     */
    public void updateToSearch(final Question q, final QuesAnswerUpdateForm param) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                Date date = new Date();
                HistoryListDataForSearch data = new HistoryListDataForSearch();
                data.setSend_time(DateTimeUtil.toString(date, DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
                data.setAnswer_tag(param.getAnswer_tag());
                data.setAnswer_content(param.getAnswer_content());
                boolean b = SearchEngineAdapterClient.getSearchEngineAdapter().update(TABLE_NAME,
                        QUESTION_TABLE_PREFIX + q.getQuestion_id().toString(), data);
                try {
                    if (b) {
                        logger.info("更新问与答" + TABLE_NAME + "，row_id：" + q.getQuestion_id().toString() + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("更新问与答" + TABLE_NAME + "，row_id：" + q.getQuestion_id().toString() + "到搜索引擎失败",
                            e.getMessage());
                }
            }
        });
    }
    
    /*
     * 
     * 滚动直播更新到引擎
     */
    public void updateToSearch(final String position_str, final RollingMsgUpdateForm param,
            final RollingMsg rollingMsg) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                HistoryListDataForSearch data = new HistoryListDataForSearch();
                data.setPositionStrByTime(position_str);
                data.setContent(param.getMsg_content());
                /* 该字段暂无用途，统一置为1 */
                // map.put("send_status", 1);
                boolean b = SearchEngineAdapterClient.getSearchEngineAdapter().update(TABLE_NAME,
                        ROLLINGMSG_TABLE_PREFIX + rollingMsg.getRollingmsg_id().toString(), data);
                try {
                    if (b) {
                        logger.info("更新直播" + TABLE_NAME + "，row_id：" + rollingMsg.getRollingmsg_id() + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("更新直播" + TABLE_NAME + "，row_id：" + rollingMsg.getRollingmsg_id() + "到搜索引擎失败",
                            e.getMessage());
                }
            }
        });
    }
    
    /*
     * 观点说更新到引擎
     */
    public void updateToSearch(final ViewpointMsg msg, final Integer publicFlag, final String checkFlag) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                Long viewpointId = msg.getViewpoint_id();
                HistoryListDataForSearch data = new HistoryListDataForSearch();
                Long viewpoint_tag = msg.getViewpoint_tag();
                String position_str = PositionStrUtil.getPositionStr();
                data.setContent(msg.getViewpoint_content());
                data.setLabel(msg.getViewpoint_abstract());
                data.setTag_id(String.valueOf(viewpoint_tag));
                data.setTag_name(msg.getViewpoint_tag_name());
                data.setPositionStrByTime(position_str);
                data.setPublic_flag(ValueUtil.getString(publicFlag));
                JSONObject contentJson = JSON.parseObject(msg.getViewpoint_content());
                String viewpoint_title = contentJson.getString("title");
                data.setViewpoint_title(viewpoint_title);
                data.setPublic_review_status(checkFlag);
                boolean b = SearchEngineAdapterClient.getSearchEngineAdapter().update(TABLE_NAME,
                        VIEWPOINT_TABLE_PREFIX + viewpointId.toString(), data);
                try {
                    if (b) {
                        logger.info("更新观点说" + TABLE_NAME + "，row_id：" + viewpointId.toString() + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("更新观点说" + TABLE_NAME + "，row_id：" + viewpointId.toString() + "到搜索引擎失败",
                            e.getMessage());
                }
                
            }
        });
    }
    
    //删除记录
    public void deleteToSearch(final Integer tableType, final String id) {
        pool.execute(new Runnable() {
            @Override
            public void run() {
                boolean b = false;
                if (tableType.equals(QUESTION_TYPE)) {
                    b = SearchEngineAdapterClient.getSearchEngineAdapter().delete(TABLE_NAME,
                            QUESTION_TABLE_PREFIX + id);
                } else if (ROLLINGMSG_TYPE.equals(tableType)) {
                    b = SearchEngineAdapterClient.getSearchEngineAdapter().delete(TABLE_NAME,
                            ROLLINGMSG_TABLE_PREFIX + id);
                } else if (VIEWPOINT_TYPE.equals(tableType)) {
                    b = SearchEngineAdapterClient.getSearchEngineAdapter().delete(TABLE_NAME,
                            VIEWPOINT_TABLE_PREFIX + id);
                }
                try {
                    if (b) {
                        logger.info("删除记录" + TABLE_NAME + "，记录类型：" + tableType + "到搜索引擎成功");
                    }
                } catch (Exception e) {
                    logger.info("更新观点说" + TABLE_NAME + "，记录类型：" + tableType + "到搜索引擎失败",
                            e.getMessage());
                }
            }
        });
    }
    
    //删除记录
    public Object deleteAll() {
        return SearchEngineAdapterClient.getSearchEngineAdapter().deleteAll();
    }
    
}
